<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="发送人" prop="type">
        <el-input
          v-model="queryParams.senderName"
          placeholder="请输入发送人"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送时间" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :editable="false"
          :default-time="['00:00:00', '23:59:59']"
          clearable
        />
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
        搜索
      </el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新建群发
        </el-button>
        <!-- v-hasPermi="['system:article:add']" -->
      </el-col>
      <right-toolbar
        :search="false"
        :showSearch.sync="showSearch"
        @queryTable="getList"
      />
    </el-row>
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="内容" align="center" prop="content" show-overflow-tooltip />
      <el-table-column label="发送时间" align="center" prop="createTime" />
      <el-table-column label="发送人" align="center" prop="senderName" />
      <el-table-column label="条数" align="center" prop="sendMessageCount" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加对话框 -->
    <el-dialog
      title="添加消息"
      :visible.sync="msgShow"
      width="1100px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-row :gutter="24">
        <el-col :span="10">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="getCustomerList"
          >
            添加联系人
          </el-button>
          <div class="peopleBox" v-if="peopleList.length > 0">
            <div v-for="item in peopleList" class="people_item" :key="item.userId">
              <div>{{ item.nickName }}</div>
              <i class="el-icon-delete" @click="removeCustomer(item.userId)" />
            </div>
          </div>
          <div v-if="peopleList.length > 0">
            添加联系人数量
            <span style="color: red; margin-left: 4px">{{ peopleList.length || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="13">
          <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px">
            <el-form-item label="消息标题" prop="title">
              <el-input v-model="editForm.title" placeholder="请输入消息标题" />
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input
                v-model="editForm.content"
                type="textarea"
                :maxlength="1000"
                :autosize="{ minRows: 10, maxRows: 18 }"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 关联客户 -->
    <el-dialog
      title="关联客户"
      :visible.sync="customerShow"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        :model="searchParams"
        ref="searchQuery"
        size="small"
        inline
        label-width="68px"
      >
        <el-form-item label="类型">
          <el-select v-model="searchParams.userType" placeholder="请选择类型">
            <el-option
              v-for="item in userTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input
            v-model="searchParams.keywords"
            placeholder="请输入用户名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleCustomer"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetCustomer"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        ref="tableRef"
        :data="customerList"
        :row-key="rowKey"
        @select="handleSelectionChange"
        @select-all="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" align="center" prop="nickName" />
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.userType | enumUserType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="电话号码" align="center" prop="phonenumber" />
        <el-table-column label="角色" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.approver == 0 ? "无" : "批准人" }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCustomer">取 消</el-button>
        <el-button type="primary" @click="submitCustomer">确 定</el-button>
      </div>
      <pagination
        v-show="customerTotal > 0"
        :total="customerTotal"
        :page.sync="searchParams.pageNum"
        :limit.sync="searchParams.pageSize"
        @pagination="getCustomerList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { systemList, addMessage, messageMsgUser } from "@/api/message/index";

export default {
  name: "message",
  data() {
    return {
      loading: false, // 遮罩层
      showSearch: true, // 显示搜索条件
      dataList: [], // 消息列表
      total: 0, // 总条数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        content: null,
        msgType: 1,
      },
      msgShow: false, // 消息弹窗
      customerShow: false, // 关联客户弹窗
      customerList: [], // 客户列表
      customerTotal: 0, // 客户总条数
      // 客户查询参数
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: "",
        userType: "",
      },
      userTypes: [
        { value: "02", label: "委托单位" },
        { value: "03", label: "一级消防注册工程师" },
        { value: "04", label: "中级消防设施操作员" },
        { value: "05", label: "平台维修员" },
      ],
      editForm: {}, // 表单参数
      rules: {
        // 表单校验
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "消息内容不能为空", trigger: "blur" }],
      },
      dateRange: [], // 临时选中日期范围
      peopleList: [],
      selectionList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    rowKey(row) {
      return row.userId;
    },
    /** 查询协议列表 */
    getList() {
      this.loading = true;
      systemList(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.dateRange && this.dateRange.length) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.senderName = "";
      this.queryParams.pageNum = 1;
      this.dateRange = [];
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.msgShow = true;
      this.peopleList = [];
      this.selectionList = [];
    },
    // 取消按钮
    handleCancel() {
      this.msgShow = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.editForm = {
        title: null,
        content: null,
        userIds: [],
        msgType: 1,
      };
      this.resetForm("editForm");
    },
    /** 查询客户列表 */
    getCustomerList() {
      this.customerShow = true;
      messageMsgUser(this.searchParams).then((res) => {
        this.customerList = res.rows;
        this.customerTotal = res.total;
        let list = this.peopleList;
        this.$nextTick(() => {
          this.$refs.tableRef.clearSelection();
          this.customerList.forEach((row) => {
            if (list.some((it) => it.userId == row.userId)) {
              this.$refs.tableRef.toggleRowSelection(row);
            }
          });
        });
      });
    },
    // 搜素客户
    handleCustomer() {
      this.searchParams.pageNum = 1;
      this.getCustomerList();
    },
    // 重置客户搜索
    resetCustomer() {
      this.searchParams.userType = "";
      this.searchParams.keywords = "";
      this.searchParams.pageNum = 1;
      this.resetForm("searchQuery");
      this.handleCustomer();
    },
    // 移除客户
    removeCustomer(userId) {
      this.peopleList = this.peopleList.filter((i) => i.userId != userId);
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.selectionList = val;
    },
    // 确认选择客户
    submitCustomer() {
      const mergedList = [...new Set([...this.peopleList, ...this.selectionList])];
      this.peopleList = this.removeRepet(mergedList, 'userId');;
      this.closeCustomer();
    },
    // 去重
    removeRepet(list, key) {
      let map = new Map();
      list.forEach((item) => {
        if (!map.has(item[key])) map.set(item[key], item);
      });
      return [...map.values()];
    },
    // 取消选择客户
    closeCustomer() {
      this.selectionList = [];
      this.searchParams.pageNum = 1;
      this.customerShow = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          if (this.peopleList.length == 0) {
            return this.$modal.msgError("请选择联系人");
          } else {
            let data = Object.assign({}, this.editForm);
            data.userId = this.peopleList.map((i) => i.userId).join(",");
            addMessage(data).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.peopleList = [];
              this.msgShow = false;
              this.getList();
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss">
.el-tooltip__popper {
  max-width: 50%;
}
.peopleBox {
  border: 1px solid gainsboro;
  border-radius: 4px;
  margin: 10px 0;
  max-height: 500px;
  overflow-y: auto;
  .people_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    transition: all 0.5s;
    &:hover {
      color: #409eff;
      background-color: #e8f4ff;
    }
    .el-icon-delete:hover {
      color: #f56c6c;
      cursor: pointer;
    }
  }
}
</style>
